<template>
    <div class="my-posts-panel">
        <div class="posts-container">
            <div v-if="loading && posts.length === 0" class="loading-state">
                <el-icon class="is-loading">
                    <Loading />
                </el-icon>
                <span>加载中...</span>
            </div>

            <template v-else>
                <div v-for="post in posts" :key="post.post_id" class="my-post-item">
                    <div class="post-header">
                        <div class="post-time">{{ formatTime(post.created_at) }}</div>
                        <div class="post-actions">
                            <el-button size="small" @click="handleEdit(post)" class="edit-btn">
                                <el-icon>
                                    <Edit />
                                </el-icon>
                                编辑
                            </el-button>
                            <el-button size="small" type="danger" @click="handleDelete(post.post_id)"
                                class="delete-btn">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                                删除
                            </el-button>
                        </div>
                    </div>

                    <div class="post-content">
                        {{ post.content }}
                    </div>

                    <!-- 图片展示 -->
                    <div v-if="getPostImages(post).length > 0" class="post-images">
                        <div class="images-grid" :class="`images-${Math.min(getPostImages(post).length, 4)}`">
                            <img v-for="(image, index) in getPostImages(post)" :key="index" :src="image"
                                :alt="`图片${index + 1}`" class="post-image"
                                @click="previewImage(getPostImages(post), index)" />
                        </div>
                    </div>

                    <div class="post-stats">
                        <span class="likes">
                            <el-icon>
                                <Star />
                            </el-icon>
                            {{ post.like_count }} 赞
                        </span>
                        <span class="comments">
                            <el-icon>
                                <ChatDotRound />
                            </el-icon>
                            {{ post.comment_count }} 评论
                        </span>
                    </div>
                </div>

                <div v-if="posts.length === 0" class="empty-state">
                    <el-empty description="您还没有发布过动态" />
                </div>

                <div v-if="hasMore" class="load-more">
                    <el-button :loading="loading" @click="loadMore" class="load-more-btn">
                        {{ loading ? '加载中...' : '加载更多' }}
                    </el-button>
                </div>
            </template>
        </div>

        <!-- 编辑对话框 -->
        <PostEdit v-model:visible="editDialogVisible" :post="editingPost" @success="handleEditSuccess" />

        <!-- 图片预览 -->
        <el-dialog v-model="imagePreviewVisible" title="图片预览" width="80%" top="5vh" align-center
            class="image-preview-dialog">
            <div class="image-preview">
                <img :src="currentPreviewImage" alt="预览图片" class="preview-image" />
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Close, Loading, Edit, Delete } from '@element-plus/icons-vue'
import { usePostsStore } from '@/stores/posts'
import { useUserStore } from '@/stores/user'
import PostEdit from './PostEdit.vue'

const emit = defineEmits(['close', 'post-updated', 'post-deleted'])

const postsStore = usePostsStore()
const userStore = useUserStore()

const posts = ref([])
const loading = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = ref(10)

const editDialogVisible = ref(false)
const editingPost = ref(null)
const imagePreviewVisible = ref(false)
const currentPreviewImage = ref('')

// 获取帖子图片
const getPostImages = (post) => {
    if (!post.images || post.images === 'null' || post.images === null) {
        return []
    }

    try {
        if (Array.isArray(post.images)) {
            return post.images.filter(img => img && img.trim())
        }

        if (typeof post.images === 'string') {
            const images = post.images.split(',').filter(img => img && img.trim())
            return images.map(img => img.trim())
        }

        return []
    } catch (error) {
        console.error('图片数据解析错误:', error)
        return []
    }
}

// 加载我的动态
const fetchMyPosts = async () => {
    try {
        loading.value = true
        const userId = userStore.getUserId()
        const response = await postsStore.fetchPosts({
            user_id: userId,
            page: page.value,
            pageSize: pageSize.value
        })

        if (response.code === 0) {
            const newPosts = response.data.list || []

            if (page.value === 1) {
                posts.value = newPosts
            } else {
                posts.value = [...posts.value, ...newPosts]
            }

            // 检查是否还有更多数据
            hasMore.value = newPosts.length === pageSize.value
        } else {
            throw new Error(response.msg)
        }
    } catch (error) {
        console.error('加载我的动态失败:', error)
        ElMessage.error('加载失败')
    } finally {
        loading.value = false
    }
}

// 加载更多
const loadMore = async () => {
    if (!hasMore.value || loading.value) return

    page.value += 1
    await fetchMyPosts()
}

// 编辑动态
const handleEdit = (post) => {
    editingPost.value = post
    editDialogVisible.value = true
}

// 删除动态
const handleDelete = async (postId) => {
    try {
        await ElMessageBox.confirm('确定要删除这条动态吗？', '提示', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })

        await postsStore.removePost(postId)

        // 从列表中移除
        posts.value = posts.value.filter(post => post.post_id !== postId)
        emit('post-deleted')
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 编辑成功
const handleEditSuccess = () => {
    editDialogVisible.value = false
    editingPost.value = null
    // 重新加载数据
    page.value = 1
    fetchMyPosts()
    emit('post-updated')
}

// 图片预览
const previewImage = (images, index) => {
    currentPreviewImage.value = images[index]
    imagePreviewVisible.value = true
}

// 关闭面板
const handleClose = () => {
    emit('close')
}

// 时间格式化
const formatTime = (timeString) => {
    if (!timeString) return ''
    const date = new Date(timeString)
    return date.toLocaleString()
}

onMounted(() => {
    fetchMyPosts()
})
</script>

<style scoped>
.my-posts-panel {
    max-height: 70vh;
    display: flex;
    flex-direction: column;
}

.panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;
    margin-bottom: 16px;
}

.panel-header h3 {
    margin: 0;
    color: #303133;
}

.posts-container {
    flex: 1;
    overflow-y: auto;
    padding: 4px;
}

.my-post-item {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9ff 100%);
    border-radius: 16px;
    padding: 20px;
    margin-bottom: 16px;
    border: 1px solid rgba(255, 255, 255, 0.8);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.my-post-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.my-post-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.post-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.post-time {
    font-size: 12px;
    color: #909399;
    background: rgba(102, 126, 234, 0.1);
    padding: 4px 8px;
    border-radius: 12px;
}

.post-actions {
    display: flex;
    gap: 8px;
}

.edit-btn {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    border: none;
    color: white;
    border-radius: 8px;
}

.delete-btn {
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
    border: none;
    color: white;
    border-radius: 8px;
}

.post-content {
    margin-bottom: 16px;
    line-height: 1.6;
    color: #2c3e50;
    word-break: break-word;
    font-size: 14px;
}

.post-images {
    margin-bottom: 16px;
}

.images-grid {
    display: grid;
    gap: 8px;
    border-radius: 12px;
    overflow: hidden;
}

.images-1 {
    grid-template-columns: 1fr;
    max-width: 400px;
}

.images-2 {
    grid-template-columns: 1fr 1fr;
}

.images-3,
.images-4 {
    grid-template-columns: repeat(3, 1fr);
}

.post-image {
    width: 100%;
    height: 120px;
    object-fit: cover;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid transparent;
}

.post-image:hover {
    transform: scale(1.05);
    border-color: #667eea;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.post-stats {
    font-size: 13px;
    color: #5a6c7d;
    display: flex;
    gap: 20px;
    align-items: center;
}

.post-stats .likes,
.post-stats .comments {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 4px 8px;
    background: rgba(102, 126, 234, 0.08);
    border-radius: 12px;
}

.loading-state {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px;
    color: #667eea;
    gap: 8px;
    font-size: 16px;
}

.empty-state {
    padding: 40px 0;
    text-align: center;
}

.load-more {
    text-align: center;
    padding: 20px;
}

.load-more-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
    border-radius: 10px;
    padding: 10px 24px;
    transition: all 0.3s ease;
}

.load-more-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
}

.image-preview {
    text-align: center;
}

.preview-image {
    max-width: 100%;
    max-height: 60vh;
    object-fit: contain;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

:deep(.image-preview-dialog .el-dialog) {
    border-radius: 16px;
    overflow: hidden;
}

:deep(.image-preview-dialog .el-dialog__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    margin: 0;
    padding: 16px 20px;
}

:deep(.image-preview-dialog .el-dialog__title) {
    color: white;
    font-weight: 600;
}
</style>
